<?php

namespace app\admin\controller\shop;

use addons\shop\model\TemplateMsg;
use app\common\controller\Backend;
use app\admin\model\shop\OrderGoods;
use app\admin\model\shop\OrderAftersales;
use app\admin\model\shop\OrderAction;
use app\admin\model\shop\OrderElectronics;
use app\common\model\User;
use app\admin\model\DividendPool;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;
use Exception;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\shop\Order
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'id,order_sn';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shop\Order;
        $this->view->assign("orderstateList", $this->model->getOrderstateList());
        $this->view->assign("shippingstateList", $this->model->getShippingstateList());
        $this->view->assign("paystateList", $this->model->getPaystateList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit, , $alias) = $this->buildparams();
            $a = reset($alias);
            $list = $this->model
                ->field($a . '.*,oe.print_template,oe.id oe_id')
                ->alias($alias)
                ->where($where)
                ->join('shop_order_electronics oe', $a . '.order_sn=oe.order_sn and oe.status=0', 'LEFT')
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $config = get_addon_config('shop');
        $this->assignconfig('shop', $config);
        return $this->view->fetch();
    }

    //发货单列表
    public function orderList()
    {
        $ids = $this->request->post('ids/a');
        if (empty($ids)) {
            $this->error('参数错误');
        }
        $orderList = $this->model->with(['User', 'OrderGoods'])->order('createtime desc')->where('id', 'IN', $ids)->select();

        foreach ($orderList as $index => $item) {
            if ($item->user) {
                $item->user->visible(['id', 'nickname', 'avatar']);
            }
        }

        $orderList = collection($orderList)->toArray();
        foreach ($orderList as $index => &$item) {
            $nums = 0;
            foreach ($item['order_goods'] as $key => $goods) {
                if ($goods['salestate'] == 4 || $goods['salestate'] == 5) {
                    unset($item['order_goods'][$key]);
                }
                $nums += $goods['nums'];
            }
            $item['nums'] = $nums;
        }
        $this->success('获取成功', '', ['orderList' => $orderList]);
    }

    //订单详情
    public function detail()
    {
        $id = $this->request->param('ids');
        if (!$id) {
            $this->error('参数错误');
        }
        $row = $this->model->field('o.*,sum(s.refund) refund')->with(['User', 'OrderGoods', 'OrderAction'])
            ->where('o.id', $id)
            ->alias('o')
            ->join('shop_order_aftersales s', 'o.id=s.order_id and s.status=2 and s.type <> 3', 'LEFT')
            ->find();

        if (!$row) {
            $this->error('记录未找到');
        }

        //计算单个商品折扣后的价格
        $saleamount = bcsub($row['saleamount'], $row['shippingfee'], 2);
        $saleratio = $row['goodsprice'] > 0 ? bcdiv($saleamount, $row['goodsprice'], 10) : 1;
        $saleremains = $saleamount;
        $orderItem = $row->order_goods;
        foreach ($orderItem as $index => $item) {
            if (!isset($orderItem[$index + 1])) {
                $saleprice = $saleremains;
            } else {
                $saleprice = $row['discount'] == 0 ? bcmul($item['price'], $item['nums'], 2) : bcmul(bcmul($item['price'], $item['nums'], 2), $saleratio, 2);
            }
            $saleremains = bcsub($saleremains, $saleprice, 2);
            $item['saleprice'] = $saleprice;
        }

        $config = get_addon_config('shop');
        $this->assignconfig('shop', $config);

        $this->view->assign('row', $row);
        return $this->view->fetch();
    }

    //订单状态操作
    public function edit_status()
    {
        // $orderstate = $this->request->post('orderstate');
        // $paystate = $this->request->post('paystate');
        // $order_id = $this->request->post('order_id');
        $orderstate = $this->request->param('orderstate') ?: $this->request->post('orderstate');
        $paystate = $this->request->param('paystate') ?: $this->request->post('paystate');
        $order_id = $this->request->param('order_id') ?: $this->request->post('order_id');

        $order = $this->model->where('id', $order_id)->find();

        if (!$order) {
            $this->error('未找到订单记录');
        }
        //取消
        if ($orderstate == 1 && $order->orderstate == 0 && $order->paystate == 0) {
            $order->orderstate = 1;
            $order->canceltime = time();
            $order->save();
            $this->success('取消成功');
        }
        // 支付
        if ($paystate == 1 && $order->orderstate == 0 && $order->paystate == 0) {
            
            Db::startTrans();
            try {
                $order->paystate = 1;
                $order->paytype = 'system';
                $order->method = 'system';
                $order->payamount = $order->saleamount;
                $amount = $order->payamount; // 订单总金额
                // 计算积分（订单金额的20%和40%）
                $shoppingIntegral = $amount * 0.2; 
                $couponIntegral = $amount * 0.4; 

                $order->paytime = time();
                // 总积分
                // $order->total_point = $shoppingIntegral + $couponIntegral;
                // // 已返积分
                // $order->fan_point = 0;
                // // 剩余积分
                // $order->sheng_point = $shoppingIntegral + $couponIntegral;

                $order->shoppingIntegral = $shoppingIntegral;
                $order->couponIntegral = $couponIntegral;

                $order->save();


                // 更新用户积分并记录变动
                $user = User::find($order->user_id);
                
                // 记录购物积分变动
                $beforeShopping = $user->shopping_integral;
                $user->shopping_integral += $shoppingIntegral;
                $afterShopping = $user->shopping_integral;
                
                // 记录消费券变动
                $beforeCoupon = $user->coupon_integral;
                $user->coupon_integral += $couponIntegral;
                $afterCoupon = $user->coupon_integral;
                
                $user->save();

                
                // 记录积分变动日志
                \app\admin\model\user\money\Log::recordShoppingIntegral(
                    $user->id,
                    $shoppingIntegral,
                    $beforeShopping,
                    $afterShopping,
                    '订单支付获得购物积分，订单号：' . $order->order_sn
                );
                
                \app\admin\model\user\money\Log::recordCouponIntegral(
                    $user->id,
                    $couponIntegral,
                    $beforeCoupon,
                    $afterCoupon,
                    '订单支付赠送消费券，订单号：' . $order->order_sn
                );

                // 订单利润的20%进入分红池
                $orderProfit = $amount * 0.2; // 订单利润为订单金额的20%
                $dividendPoolAmount = $orderProfit * 0.2; // 利润的20%进入分红池

                // 利润 增加到当期新增利润
                $dividendPoolRecord = DividendPool::where('id',1)->find();
                $newprofit_befor = $dividendPoolRecord->newprofit;
                $newprofit_after = $newprofit_befor + $orderProfit;

                \think\Log::info('[订单支付完成] 分红池记录增加前json信息：' . json_encode($dividendPoolRecord->toArray()));

                // 使用数据库更新避免并发问题
                $result = DividendPool::where('id', 1)->setInc('newprofit', $orderProfit);
                if ($result) {
                    \think\Log::info(
                    '[订单支付完成] 原新增利润：' . $newprofit_befor . 
                    '，更新后新增利润：' . $newprofit_after . 
                    '，订单号：' . $order->order_sn . 
                    '，订单金额：' . $amount . 
                    '，订单利润：' . $orderProfit);
                }else{
                    \think\Log::error('[订单支付完成] 更新当期新增利润失败，订单号：' . $order->order_sn);
                }

                $dividendPool = new DividendPool();
                $dividendPool->addBalance(
                    $dividendPoolAmount, 
                    $order->id, 
                    null, 
                    '订单支付利润20%进入分红池，订单号：' . $order->order_sn . '，订单金额：' . $amount
                );
                

                // 订单利润的40% 分配给团队
                $teamAmount = $orderProfit * 0.4;
                // 直推分配50%
                $zhituiAmount = $teamAmount * 0.5;

                // 查询下单用户的直接推荐人zhitui_id
                /*$zhituiId = $user->zhitui_id;
                if ($zhituiId) {
                    // 把zhituiAmount分配到zhituiId用户的权益值，记录用户权益值变动
                    $zhituiUser = User::find($zhituiId);
                    if ($zhituiUser) {
                        $beforeMoney = $zhituiUser->money;
                        $zhituiUser->money += $zhituiAmount;
                        $afterMoney = $zhituiUser->money;
                        // promotion_bonus推广红包 增加
                        $zhituiUser->promotion_bonus += $zhituiAmount;
                        $zhituiUser->save();
                        
                        // 记录权益值变动日志（带type2字段）
                        \app\admin\model\user\money\Log::recordPromotionEquityValue(
                            $zhituiUser->id,
                            $zhituiAmount,
                            $beforeMoney,
                            $afterMoney,
                            '直推订单奖励，订单号：' . $order->order_sn . '，订单金额：' . $amount
                        );
                        
                        \think\Log::info('[直推奖励] 推荐人ID: ' . $zhituiId . ', 获得权益值: ' . $zhituiAmount . ', 订单号: ' . $order->order_sn);
                    }
                }
                */


                // 间推分配12.5%
                /*$jiantuiAmount = $teamAmount * 0.125;
                // 查询下单用户的间接推荐人jiantui_id
                $jiantuiId = $user->jiantui_id;
                if ($jiantuiId) {
                    // 把jiantuiAmount分配到jiantuiId用户的权益值，记录用户权益值变动
                    $jiantuiUser = User::find($jiantuiId);
                    if ($jiantuiUser) {
                        $beforeMoney = $jiantuiUser->money;
                        $jiantuiUser->money += $jiantuiAmount;
                        $afterMoney = $jiantuiUser->money;
                        // promotion_bonus推广红包 增加
                        $jiantuiUser->promotion_bonus += $jiantuiAmount;
                        $jiantuiUser->save();
                        
                        // 记录权益值变动日志（带type2字段）
                        \app\admin\model\user\money\Log::recordPromotionEquityValue(
                            $jiantuiUser->id,
                            $jiantuiAmount,
                            $beforeMoney,
                            $afterMoney,
                            '间推订单奖励，订单号：' . $order->order_sn . '，订单金额：' . $amount
                        );
                        
                        \think\Log::info('[间推奖励] 推荐人ID: ' . $jiantuiId . ', 获得权益值: ' . $jiantuiAmount . ', 订单号: ' . $order->order_sn);
                    }
                }
                */

                // 团队等级分配37.5%
                $dengjiAmount = $teamAmount * 0.375;

                // V1等级分33.3%
                $V1Amount = $dengjiAmount * 0.333;
                // 查用户表 team_level字段是V1的用户，如果存在则进行分配，所有V1用户 平分V1Amount，平分的金额转到用户权益值，记录用户权益值变化
                $V1Users = \app\admin\model\User::where('team_level', 'V1')->select();
                if ($V1Users) {
                    $V1UserCount = count($V1Users);
                    if ($V1UserCount > 0) {
                        $perV1UserAmount = floor($V1Amount / $V1UserCount); // 去掉小数部分
                        foreach ($V1Users as $V1User) {
                            $beforeMoney = $V1User->money;
                            $V1User->money += $perV1UserAmount;
                            $afterMoney = $V1User->money;
                            // green_integral绿色积分 增加
                            $V1User->green_integral += $perV1UserAmount;
                            $V1User->save();
                            
                            // 记录权益值变动日志
                            \app\admin\model\user\money\Log::recordTeamEquityValue(
                                $V1User->id,
                                $perV1UserAmount,
                                $beforeMoney,
                                $afterMoney,
                                'V1等级奖励，订单号：' . $order->order_sn . '，订单金额：' . $amount,
                                '绿色积分'  // type2字段设置为绿色积分
                            );
                            
                            \think\Log::info('[V1等级奖励] 用户ID: ' . $V1User->id . ', 获得权益值: ' . $perV1UserAmount . ', 订单号: ' . $order->order_sn);
                        }
                        // 增加详细日志记录
                        \think\Log::info('[V1等级奖励详情] 团队等级总分配金额: ' . $dengjiAmount . ', V1等级总金额: ' . $V1Amount . ', V1用户数量: ' . $V1UserCount . ', 每人平均分得金额: ' . $perV1UserAmount . ', 订单号: ' . $order->order_sn);
                    } else {
                        \think\Log::info('[V1等级奖励] V1用户数量为0，未进行分配，订单号: ' . $order->order_sn);
                    }
                } else {
                    \think\Log::info('[V1等级奖励] 未找到V1等级用户，未进行分配，订单号: ' . $order->order_sn);
                }
                
                // V2等级分26.6%
                $V2Amount = $dengjiAmount * 0.266;
                // 查用户表 team_level字段是V2的用户，如果存在则进行分配，所有V2用户 平分V2Amount，平分的金额转到用户权益值，记录用户权益值变化
                $V2Users = \app\admin\model\User::where('team_level', 'V2')->select();
                if ($V2Users) {
                    $V2UserCount = count($V2Users);
                    if ($V2UserCount > 0) {
                        $perV2UserAmount = floor($V2Amount / $V2UserCount); // 去掉小数部分
                        foreach ($V2Users as $V2User) {
                            $beforeMoney = $V2User->money;
                            $V2User->money += $perV2UserAmount;
                            $afterMoney = $V2User->money;
                            // green_integral绿色积分 增加
                            $V2User->green_integral += $perV2UserAmount;
                            $V2User->save();
                            
                            // 记录权益值变动日志
                            \app\admin\model\user\money\Log::recordTeamEquityValue(
                                $V2User->id,
                                $perV2UserAmount,
                                $beforeMoney,
                                $afterMoney,
                                'V2等级奖励，订单号：' . $order->order_sn . '，订单金额：' . $amount,
                                '绿色积分'  // type2字段设置为绿色积分
                            );
                            
                            \think\Log::info('[V2等级奖励] 用户ID: ' . $V2User->id . ', 获得权益值: ' . $perV2UserAmount . ', 订单号: ' . $order->order_sn);
                        }
                        // 增加详细日志记录
                        \think\Log::info('[V2等级奖励详情] 团队等级总分配金额: ' . $dengjiAmount . ', V2等级总金额: ' . $V2Amount . ', V2用户数量: ' . $V2UserCount . ', 每人平均分得金额: ' . $perV2UserAmount . ', 订单号: ' . $order->order_sn);
                    } else {
                        \think\Log::info('[V2等级奖励] V2用户数量为0，未进行分配，订单号: ' . $order->order_sn);
                    }
                } else {
                    \think\Log::info('[V2等级奖励] 未找到V2等级用户，未进行分配，订单号: ' . $order->order_sn);
                }

                // V3等级分23.3%
                $V3Amount = $dengjiAmount * 0.233;
                // 查用户表 team_level字段是V3的用户，如果存在则进行分配，所有V3用户 平分V3Amount，平分的金额转到用户权益值，记录用户权益值变化
                $V3Users = \app\admin\model\User::where('team_level', 'V3')->select();
                if ($V3Users) {
                    $V3UserCount = count($V3Users);
                    if ($V3UserCount > 0) {
                        $perV3UserAmount = floor($V3Amount / $V3UserCount); // 去掉小数部分
                        foreach ($V3Users as $V3User) {
                            $beforeMoney = $V3User->money;
                            $V3User->money += $perV3UserAmount;
                            $afterMoney = $V3User->money;
                            // green_integral绿色积分 增加
                            $V3User->green_integral += $perV3UserAmount;
                            $V3User->save();
                            
                            // 记录权益值变动日志
                            \app\admin\model\user\money\Log::recordTeamEquityValue(
                                $V3User->id,
                                $perV3UserAmount,
                                $beforeMoney,
                                $afterMoney,
                                'V3等级奖励，订单号：' . $order->order_sn . '，订单金额：' . $amount,
                                '绿色积分'  // type2字段设置为绿色积分
                            );
                            
                            \think\Log::info('[V3等级奖励] 用户ID: ' . $V3User->id . ', 获得权益值: ' . $perV3UserAmount . ', 订单号: ' . $order->order_sn);
                        }
                        // 增加详细日志记录
                        \think\Log::info('[V3等级奖励详情] 团队等级总分配金额: ' . $dengjiAmount . ', V3等级总金额: ' . $V3Amount . ', V3用户数量: ' . $V3UserCount . ', 每人平均分得金额: ' . $perV3UserAmount . ', 订单号: ' . $order->order_sn);
                    } else {
                        \think\Log::info('[V3等级奖励] V3用户数量为0，未进行分配，订单号: ' . $order->order_sn);
                    }
                } else {
                    \think\Log::info('[V3等级奖励] 未找到V3等级用户，未进行分配，订单号: ' . $order->order_sn);
                }

                // V4等级分16.6%
                $V4Amount = $dengjiAmount * 0.166;
                // 查用户表 team_level字段是V4的用户，如果存在则进行分配，所有V4用户 平分V4Amount，平分的金额转到用户权益值，记录用户权益值变化
                $V4Users = \app\admin\model\User::where('team_level', 'V4')->select();
                if ($V4Users) {
                    $V4UserCount = count($V4Users);
                    if ($V4UserCount > 0) {
                        $perV4UserAmount = floor($V4Amount / $V4UserCount); // 去掉小数部分
                        foreach ($V4Users as $V4User) {
                            $beforeMoney = $V4User->money;
                            $V4User->money += $perV4UserAmount;
                            $afterMoney = $V4User->money;
                            // green_integral绿色积分 增加
                            $V4User->green_integral += $perV4UserAmount;
                            $V4User->save();
                            
                            // 记录权益值变动日志
                            \app\admin\model\user\money\Log::recordTeamEquityValue(
                                $V4User->id,
                                $perV4UserAmount,
                                $beforeMoney,
                                $afterMoney,
                                'V4等级奖励，订单号：' . $order->order_sn . '，订单金额：' . $amount,
                                '绿色积分'  // type2字段设置为绿色积分
                            );
                            
                            \think\Log::info('[V4等级奖励] 用户ID: ' . $V4User->id . ', 获得权益值: ' . $perV4UserAmount . ', 订单号: ' . $order->order_sn);
                        }
                        // 增加详细日志记录
                        \think\Log::info('[V4等级奖励详情] 团队等级总分配金额: ' . $dengjiAmount . ', V4等级总金额: ' . $V4Amount . ', V4用户数量: ' . $V4UserCount . ', 每人平均分得金额: ' . $perV4UserAmount . ', 订单号: ' . $order->order_sn);
                    } else {
                        \think\Log::info('[V4等级奖励] V4用户数量为0，未进行分配，订单号: ' . $order->order_sn);
                    }
                } else {
                    \think\Log::info('[V4等级奖励] 未找到V4等级用户，未进行分配，订单号: ' . $order->order_sn);
                }
                
                \think\Log::info('[订单支付] 订单号: ' . $order->order_sn . ', 订单金额: ' . $amount . ', 利润: ' . $orderProfit . ', 分红池增加: ' . $dividendPoolAmount);



                // 更新团队业绩
                // 下单用户的直接推荐人id,查询用户表 id是直接推荐人id的和zhitui_id是直接推荐人id的和jiantui_id是直接推荐人id的所有用户，这些用户所有订单的总金额。总金额更新到 下单用户的直接推荐人id的 用户表yeji_team字段
                if ($user->zhitui_id) {
                    // 使用更高效的数据库查询方式计算直接推荐人团队业绩
                    $referrerTeamAmount = $this->model
                        ->alias('o')
                        ->join('fa_user u', 'o.user_id = u.id', 'LEFT')
                        ->where(function ($query) use ($user) {
                            $query->where('u.id', $user->zhitui_id)
                                ->whereOr('u.zhitui_id', $user->zhitui_id)
                                ->whereOr('u.jiantui_id', $user->zhitui_id);
                        })
                        ->sum('o.payamount');
                    
                    // 确保结果是数字格式
                    $referrerTeamAmount = $referrerTeamAmount ?: 0;
                    
                    // 更新直接推荐人的yeji_team字段
                    // 先获取原始值
                    $referrerUser = \app\admin\model\User::find($user->zhitui_id);
                    $originalReferrerYejiTeam = $referrerUser ? $referrerUser->yeji_team : 0;
                    $result = \app\admin\model\User::where('id', $user->zhitui_id)
                        ->update(['yeji_team' => $referrerTeamAmount]);
                    
                    if ($result) {
                        \think\Log::info('[yeji_team更新] 直接推荐人ID: ' . $user->zhitui_id . ', 团队业绩金额: ' . $referrerTeamAmount . ', 订单号: ' . $order->order_sn);
                    }

                    $Yejilog = new \app\admin\model\user\Yejilog();
                    $Yejilog::create([
                        'order_id' => $order->id,
                        'order_sn' => $order->order_sn,
                        'tui_type' => '直推',
                        'user_id' => $user->zhitui_id,
                        'user_name' => $user->username,
                        'before' => $originalReferrerYejiTeam,  // 团队业绩更新前的值
                        'after' => $referrerTeamAmount,        // 团队业绩更新后的值
                        'jine' => $amount,
                        'createtime' => time(),
                    ]);
                }

                // 查询用户表中 id是下单用户的间接推荐人id的和zhitui_id是间接推荐人id的和jiantui_id是间接推荐人id的所有用户，这些用户所有订单的总金额。总金额更新到下单用户的间接推荐人 的yeji_team字段
                if ($user->jiantui_id) {
                    // 使用更高效的数据库查询方式计算间接推荐人团队业绩
                    $indirectReferrerTeamAmount = $this->model
                        ->alias('o')
                        ->join('fa_user u', 'o.user_id = u.id', 'LEFT')
                        ->where(function ($query) use ($user) {
                            $query->where('u.id', $user->jiantui_id)
                                ->whereOr('u.zhitui_id', $user->jiantui_id)
                                ->whereOr('u.jiantui_id', $user->jiantui_id);
                        })
                        ->sum('o.payamount');
                    
                    // 确保结果是数字格式
                    $indirectReferrerTeamAmount = $indirectReferrerTeamAmount ?: 0;
                    
                    // 更新间接推荐人的yeji_team字段
                    // 先获取原始值
                    $indirectReferrerUser = \app\admin\model\User::find($user->jiantui_id);
                    $originalIndirectReferrerYejiTeam = $indirectReferrerUser ? $indirectReferrerUser->yeji_team : 0;
                    $result = \app\admin\model\User::where('id', $user->jiantui_id)
                        ->update(['yeji_team' => $indirectReferrerTeamAmount]);
                    
                    if ($result) {
                        \think\Log::info('[yeji_team更新] 间接推荐人ID: ' . $user->jiantui_id . ', 团队业绩金额: ' . $indirectReferrerTeamAmount . ', 订单号: ' . $order->order_sn);
                    }

                    $Yejilog = new \app\admin\model\user\Yejilog();
                    $Yejilog::create([
                        'order_id' => $order->id,
                        'order_sn' => $order->order_sn,
                        'tui_type' => '间推',
                        'user_id' => $user->jiantui_id,
                        'user_name' => $user->username,
                        'before' => $originalIndirectReferrerYejiTeam,  // 团队业绩更新前的值
                        'after' => $indirectReferrerTeamAmount,        // 团队业绩更新后的值
                        'jine' => $amount,
                        // 'memo' => '团队业绩',
                        'createtime' => time(),
                    ]);
                }

                // 查询用户表中 id是下单用户的和zhitui_id是下单用户的和jiantui_id是下单用户的所有用户，这些用户所有订单的总金额。总金额更新到下单用户的yeji_team字段
                // 使用更高效的数据库查询方式计算下单用户团队业绩
                $userTeamAmount = $this->model
                    ->alias('o')
                    ->join('fa_user u', 'o.user_id = u.id', 'LEFT')
                    ->where(function ($query) use ($user) {
                        $query->where('u.id', $user->id)
                            ->whereOr('u.zhitui_id', $user->id)
                            ->whereOr('u.jiantui_id', $user->id);
                    })
                    ->sum('o.payamount');
                
                // 确保结果是数字格式
                $userTeamAmount = $userTeamAmount ?: 0;
                
                // 更新下单用户的yeji_team字段
                $originalYejiTeam = $user->yeji_team;  // 保存更新前的值
                \think\Log::info('[yeji_team更新前] 下单用户ID: ' . $user->id . ', 团队业绩金额(更新前): ' . $user->yeji_team . ', 订单号: ' . $order->order_sn);
                
                $user->yeji_team = $userTeamAmount;
                $user->save();
                \think\Log::info('[yeji_team更新后] 下单用户ID: ' . $user->id . ', 团队业绩金额(更新后): ' . $userTeamAmount . ', 订单号: ' . $order->order_sn);

                // 业绩记录
                $Yejilog = new \app\admin\model\user\Yejilog();
                // 增加记录 团队业绩增加前before 团队业绩增加后after
                $Yejilog::create([
                    'order_id' => $order->id,
                    'order_sn' => $order->order_sn,
                    'user_id' => $user->id,
                    'user_name' => $user->username,
                    'before' => $originalYejiTeam,
                    'after' => $userTeamAmount,
                    'jine' => $amount,
                    // 'memo' => '团队业绩',
                    'createtime' => time(),
                ]);


                
                // [检查用户表中 团队业绩yeji_team满足条件的升级用户等级]
                // 获取团队等级配置
                $teamLevels = \app\admin\model\Teamlevel::order('yeji_team', 'asc')->select();
                
                // 检查直接推荐人是否达到升级条件
                if ($user->zhitui_id) {
                    $referrer = \app\admin\model\User::find($user->zhitui_id);
                    if ($referrer && $referrer->yeji_team) {
                        $newTeamLevel = null;
                        foreach ($teamLevels as $teamLevel) {
                            if ($referrer->yeji_team >= $teamLevel->yeji_team) {
                                $newTeamLevel = $teamLevel->level;
                            }
                        }
                        // 如果有新的等级且与当前等级不同，则更新
                        if ($newTeamLevel && $newTeamLevel != $referrer->team_level) {
                            $referrer->team_level = $newTeamLevel;
                            $referrer->save();
                            \think\Log::info('[团队等级更新] 直接推荐人ID: ' . $referrer->id . ', 团队业绩: ' . $referrer->yeji_team . ', 新等级: ' . $newTeamLevel . ', 订单号: ' . $order->order_sn);
                        }
                    }
                }
                
                // 检查间接推荐人是否达到升级条件
                if ($user->jiantui_id) {
                    $indirectReferrer = \app\admin\model\User::find($user->jiantui_id);
                    if ($indirectReferrer && $indirectReferrer->yeji_team) {
                        $newTeamLevel = null;
                        foreach ($teamLevels as $teamLevel) {
                            if ($indirectReferrer->yeji_team >= $teamLevel->yeji_team) {
                                $newTeamLevel = $teamLevel->level;
                            }
                        }
                        // 如果有新的等级且与当前等级不同，则更新
                        if ($newTeamLevel && $newTeamLevel != $indirectReferrer->team_level) {
                            $indirectReferrer->team_level = $newTeamLevel;
                            $indirectReferrer->save();
                            \think\Log::info('[团队等级更新] 间接推荐人ID: ' . $indirectReferrer->id . ', 团队业绩: ' . $indirectReferrer->yeji_team . ', 新等级: ' . $newTeamLevel . ', 订单号: ' . $order->order_sn);
                        }
                    }
                }
                
                // 检查下单用户是否达到升级条件
                $newTeamLevel = null;
                foreach ($teamLevels as $teamLevel) {
                    if ($user->yeji_team >= $teamLevel->yeji_team) {
                        $newTeamLevel = $teamLevel->level;
                    }
                }
                // 如果有新的等级且与当前等级不同，则更新
                if ($newTeamLevel && $newTeamLevel != $user->team_level) {
                    $user->team_level = $newTeamLevel;
                    $user->save();
                    \think\Log::info('[团队等级更新] 下单用户ID: ' . $user->id . ', 团队业绩: ' . $user->yeji_team . ', 新等级: ' . $newTeamLevel . ', 订单号: ' . $order->order_sn);
                }

                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            //发送通知
            TemplateMsg::sendTempMsg(0, $order->order_sn);
            $this->success('操作成功');

        }

        //已完成
        if ($orderstate == 3 && $order->orderstate == 0 && $order->paystate == 1) {
            $order->orderstate = 3;
            $order->save();
            OrderAction::push($order->order_sn, '更改订单为已完成', '管理员');
            $this->success('操作成功');
        } elseif ($order->orderstate == 4) {
            $this->error("请完成售后后再进行操作");
        }

        $this->error('没有权限操作');
    }

    // 确认支付（不返利）
    public function yipayno()
    {
        // $orderstate = $this->request->post('orderstate');
        // $paystate = $this->request->post('paystate');
        // $order_id = $this->request->post('order_id');
        $orderstate = $this->request->param('orderstate') ?: $this->request->post('orderstate');
        $paystate = $this->request->param('paystate') ?: $this->request->post('paystate');
        $order_id = $this->request->param('order_id') ?: $this->request->post('order_id');

        $order = $this->model->where('id', $order_id)->find();

        if (!$order) {
            $this->error('未找到订单记录');
        }
        //取消
        if ($orderstate == 1 && $order->orderstate == 0 && $order->paystate == 0) {
            $order->orderstate = 1;
            $order->canceltime = time();
            $order->save();
            $this->success('取消成功');
        }
        // 支付
        if ($paystate == 1 && $order->orderstate == 0 && $order->paystate == 0) {
            
            Db::startTrans();
            try {

                $order->paystate = 1;
                $order->paytype = 'system';
                $order->method = 'system';
                $order->payamount = $order->saleamount;
                $order->paytime = time();
                // 订单数据类型为假
                $order->data_type = 0;
                $order->save();

                // 计算积分（订单金额的20%和40%）
                $amount = $order->payamount; // 订单总金额
                $shoppingIntegral = $amount * 0.2; 
                $couponIntegral = $amount * 0.4; 

                // 更新用户积分并记录变动
                $user = User::find($order->user_id);
                
                // 记录购物积分变动
                $beforeShopping = $user->shopping_integral;
                $user->shopping_integral += $shoppingIntegral;
                $afterShopping = $user->shopping_integral;
                
                // 记录消费券变动
                $beforeCoupon = $user->coupon_integral;
                $user->coupon_integral += $couponIntegral;
                $afterCoupon = $user->coupon_integral;
                
                $user->save();
                
                // 记录积分变动日志
                \app\admin\model\user\money\Log::recordShoppingIntegral(
                    $user->id,
                    $shoppingIntegral,
                    $beforeShopping,
                    $afterShopping,
                    '订单支付获得购物积分，订单号：' . $order->order_sn
                );
                
                \app\admin\model\user\money\Log::recordCouponIntegral(
                    $user->id,
                    $couponIntegral,
                    $beforeCoupon,
                    $afterCoupon,
                    '订单支付赠送消费券，订单号：' . $order->order_sn
                );


                // 更新团队业绩
                // 下单用户的直接推荐人id,查询用户表 id是直接推荐人id的和zhitui_id是直接推荐人id的和jiantui_id是直接推荐人id的所有用户，这些用户所有订单的总金额。总金额更新到 下单用户的直接推荐人id的 用户表yeji_team字段
                if ($user->zhitui_id) {
                    // 使用更高效的数据库查询方式计算直接推荐人团队业绩
                    $referrerTeamAmount = $this->model
                        ->alias('o')
                        ->join('fa_user u', 'o.user_id = u.id', 'LEFT')
                        ->where(function ($query) use ($user) {
                            $query->where('u.id', $user->zhitui_id)
                                ->whereOr('u.zhitui_id', $user->zhitui_id)
                                ->whereOr('u.jiantui_id', $user->zhitui_id);
                        })
                        ->sum('o.payamount');
                    
                    // 确保结果是数字格式
                    $referrerTeamAmount = $referrerTeamAmount ?: 0;
                    
                    // 更新直接推荐人的yeji_team字段
                    // 先获取原始值
                    $referrerUser = \app\admin\model\User::find($user->zhitui_id);
                    $originalReferrerYejiTeam = $referrerUser ? $referrerUser->yeji_team : 0;
                    $result = \app\admin\model\User::where('id', $user->zhitui_id)
                        ->update(['yeji_team' => $referrerTeamAmount]);
                    
                    if ($result) {
                        \think\Log::info('[yeji_team更新] 直接推荐人ID: ' . $user->zhitui_id . ', 团队业绩金额: ' . $referrerTeamAmount . ', 订单号: ' . $order->order_sn);
                    }

                    $Yejilog = new \app\admin\model\user\Yejilog();
                    $Yejilog::create([
                        'order_id' => $order->id,
                        'order_sn' => $order->order_sn,
                        'tui_type' => '直推',
                        'user_id' => $user->zhitui_id,
                        'user_name' => $user->username,
                        'before' => $originalReferrerYejiTeam,  // 团队业绩更新前的值
                        'after' => $referrerTeamAmount,        // 团队业绩更新后的值
                        'jine' => $amount,
                        'createtime' => time(),
                    ]);
                }

                // 查询用户表中 id是下单用户的间接推荐人id的和zhitui_id是间接推荐人id的和jiantui_id是间接推荐人id的所有用户，这些用户所有订单的总金额。总金额更新到下单用户的间接推荐人 的yeji_team字段
                if ($user->jiantui_id) {
                    // 使用更高效的数据库查询方式计算间接推荐人团队业绩
                    $indirectReferrerTeamAmount = $this->model
                        ->alias('o')
                        ->join('fa_user u', 'o.user_id = u.id', 'LEFT')
                        ->where(function ($query) use ($user) {
                            $query->where('u.id', $user->jiantui_id)
                                ->whereOr('u.zhitui_id', $user->jiantui_id)
                                ->whereOr('u.jiantui_id', $user->jiantui_id);
                        })
                        ->sum('o.payamount');
                    
                    // 确保结果是数字格式
                    $indirectReferrerTeamAmount = $indirectReferrerTeamAmount ?: 0;
                    
                    // 更新间接推荐人的yeji_team字段
                    // 先获取原始值
                    $indirectReferrerUser = \app\admin\model\User::find($user->jiantui_id);
                    $originalIndirectReferrerYejiTeam = $indirectReferrerUser ? $indirectReferrerUser->yeji_team : 0;
                    $result = \app\admin\model\User::where('id', $user->jiantui_id)
                        ->update(['yeji_team' => $indirectReferrerTeamAmount]);
                    
                    if ($result) {
                        \think\Log::info('[yeji_team更新] 间接推荐人ID: ' . $user->jiantui_id . ', 团队业绩金额: ' . $indirectReferrerTeamAmount . ', 订单号: ' . $order->order_sn);
                    }

                    $Yejilog = new \app\admin\model\user\Yejilog();
                    $Yejilog::create([
                        'order_id' => $order->id,
                        'order_sn' => $order->order_sn,
                        'tui_type' => '间推',
                        'user_id' => $user->jiantui_id,
                        'user_name' => $user->username,
                        'before' => $originalIndirectReferrerYejiTeam,  // 团队业绩更新前的值
                        'after' => $indirectReferrerTeamAmount,        // 团队业绩更新后的值
                        'jine' => $amount,
                        // 'memo' => '团队业绩',
                        'createtime' => time(),
                    ]);
                }

                // 查询用户表中 id是下单用户的和zhitui_id是下单用户的和jiantui_id是下单用户的所有用户，这些用户所有订单的总金额。总金额更新到下单用户的yeji_team字段
                // 使用更高效的数据库查询方式计算下单用户团队业绩
                $userTeamAmount = $this->model
                    ->alias('o')
                    ->join('fa_user u', 'o.user_id = u.id', 'LEFT')
                    ->where(function ($query) use ($user) {
                        $query->where('u.id', $user->id)
                            ->whereOr('u.zhitui_id', $user->id)
                            ->whereOr('u.jiantui_id', $user->id);
                    })
                    ->sum('o.payamount');
                
                // 确保结果是数字格式
                $userTeamAmount = $userTeamAmount ?: 0;
                
                // 更新下单用户的yeji_team字段
                $originalYejiTeam = $user->yeji_team;  // 保存更新前的值
                \think\Log::info('[yeji_team更新前] 下单用户ID: ' . $user->id . ', 团队业绩金额(更新前): ' . $user->yeji_team . ', 订单号: ' . $order->order_sn);
                
                $user->yeji_team = $userTeamAmount;
                $user->save();
                \think\Log::info('[yeji_team更新后] 下单用户ID: ' . $user->id . ', 团队业绩金额(更新后): ' . $userTeamAmount . ', 订单号: ' . $order->order_sn);

                // 业绩记录
                $Yejilog = new \app\admin\model\user\Yejilog();
                // 增加记录 团队业绩增加前before 团队业绩增加后after
                $Yejilog::create([
                    'order_id' => $order->id,
                    'order_sn' => $order->order_sn,
                    'user_id' => $user->id,
                    'user_name' => $user->username,
                    'before' => $originalYejiTeam,
                    'after' => $userTeamAmount,
                    'jine' => $amount,
                    // 'memo' => '团队业绩',
                    'createtime' => time(),
                ]);


                
                // [检查用户表中 团队业绩yeji_team满足条件的升级用户等级]
                // 获取团队等级配置
                $teamLevels = \app\admin\model\Teamlevel::order('yeji_team', 'asc')->select();
                
                // 检查直接推荐人是否达到升级条件
                if ($user->zhitui_id) {
                    $referrer = \app\admin\model\User::find($user->zhitui_id);
                    if ($referrer && $referrer->yeji_team) {
                        $newTeamLevel = null;
                        foreach ($teamLevels as $teamLevel) {
                            if ($referrer->yeji_team >= $teamLevel->yeji_team) {
                                $newTeamLevel = $teamLevel->level;
                            }
                        }
                        // 如果有新的等级且与当前等级不同，则更新
                        if ($newTeamLevel && $newTeamLevel != $referrer->team_level) {
                            $referrer->team_level = $newTeamLevel;
                            $referrer->save();
                            \think\Log::info('[团队等级更新] 直接推荐人ID: ' . $referrer->id . ', 团队业绩: ' . $referrer->yeji_team . ', 新等级: ' . $newTeamLevel . ', 订单号: ' . $order->order_sn);
                        }
                    }
                }
                
                // 检查间接推荐人是否达到升级条件
                if ($user->jiantui_id) {
                    $indirectReferrer = \app\admin\model\User::find($user->jiantui_id);
                    if ($indirectReferrer && $indirectReferrer->yeji_team) {
                        $newTeamLevel = null;
                        foreach ($teamLevels as $teamLevel) {
                            if ($indirectReferrer->yeji_team >= $teamLevel->yeji_team) {
                                $newTeamLevel = $teamLevel->level;
                            }
                        }
                        // 如果有新的等级且与当前等级不同，则更新
                        if ($newTeamLevel && $newTeamLevel != $indirectReferrer->team_level) {
                            $indirectReferrer->team_level = $newTeamLevel;
                            $indirectReferrer->save();
                            \think\Log::info('[团队等级更新] 间接推荐人ID: ' . $indirectReferrer->id . ', 团队业绩: ' . $indirectReferrer->yeji_team . ', 新等级: ' . $newTeamLevel . ', 订单号: ' . $order->order_sn);
                        }
                    }
                }
                
                // 检查下单用户是否达到升级条件
                $newTeamLevel = null;
                foreach ($teamLevels as $teamLevel) {
                    if ($user->yeji_team >= $teamLevel->yeji_team) {
                        $newTeamLevel = $teamLevel->level;
                    }
                }
                // 如果有新的等级且与当前等级不同，则更新
                if ($newTeamLevel && $newTeamLevel != $user->team_level) {
                    $user->team_level = $newTeamLevel;
                    $user->save();
                    \think\Log::info('[团队等级更新] 下单用户ID: ' . $user->id . ', 团队业绩: ' . $user->yeji_team . ', 新等级: ' . $newTeamLevel . ', 订单号: ' . $order->order_sn);
                }

                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            //发送通知
            TemplateMsg::sendTempMsg(0, $order->order_sn);
            $this->success('操作成功');

        }

        //已完成
        if ($orderstate == 3 && $order->orderstate == 0 && $order->paystate == 1) {
            $order->orderstate = 3;
            $order->save();
            OrderAction::push($order->order_sn, '更改订单为已完成', '管理员');
            $this->success('操作成功');
        } elseif ($order->orderstate == 4) {
            $this->error("请完成售后后再进行操作");
        }

        $this->error('没有权限操作');
    }

    //同意退款(退货)
    public function refund()
    {
        $id = $this->request->post('order_goods_id');
        if (!$id) {
            $this->error('参数错误');
        }
        $orderGoods = OrderGoods::get($id, ['Order']);
        if (empty($orderGoods)) {
            $this->error('未找到记录');
        }
        $order = $orderGoods->order;
        if (empty($order)) {
            $this->error('订单不存在');
        }

        if ($orderGoods->salestate != 3) {
            $this->error('不支持的售后状态');
        }
        $aftersales = (new OrderAftersales())
            ->where('order_goods_id', $id)
            ->where('user_id', $order->user_id)
            ->where('status', 2)
            ->order('id desc')
            ->find();

        if (!$aftersales) {
            $this->error('售后单未找到');
        }
        if ($aftersales['type'] == 2) {
            //已退货退款
            $orderGoods->salestate = 5;
            $orderGoods->save();
            //已通过，是否同步退款
            $config = get_addon_config('shop');
            if ($config['order_refund_sync']) {
                //执行同步退款
                try {
                    \app\admin\model\shop\Order::refund($order->order_sn, $order->paytype, $aftersales->refund);
                } catch (\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            //记录操作
            OrderAction::push($order->order_sn, '确认售后商品已收到', '管理员');

            $count = \app\admin\model\shop\OrderGoods::where('order_sn', $order['order_sn'])->where('salestate', 'not in', [4, 5])->count();
            if (!$count) {
                $order->refundtime = time();
                $order->orderstate = 3;
                $order->save();
            } else {
                $order->orderstate = 0;
                $order->save();
            }
        }
        $this->success('确认收货成功！');
    }


    //编辑订单信息【备注等】
    public function edit_info()
    {
        $id = $this->request->post('id');
        $field = $this->request->post('field');
        $value = $this->request->post('value');
        if (!in_array($field, ['memo'])) {
            $this->error('没有权限编辑');
        }
        $row = $this->model->with(['User'])->where('id', $id)->find();
        if (!$row) {
            $this->error('记录未找到');
        }
        $row->$field = $value;
        $row->save();
        $this->success('保存成功');
    }

    //发货
    public function deliver()
    {
        $expressname = $this->request->post('expressname');
        $expressno = $this->request->post('expressno');
        $order_id = $this->request->post('order_id');
        $type = $this->request->post('type');
        $order = $this->model->where('id', $order_id)->find();
        if (!$order) {
            $this->error('未找到订单记录');
        }
        //发货 / 修改快递信息
        if ($order->orderstate == 0 && $order->shippingstate == 0 && $order->paystate == 1 && $type == 0) {
            $order->expressname = $expressname;
            $order->expressno = $expressno;
            $order->shippingstate = 1;
            $order->shippingtime = time();
            $order->save();
            $this->success('发货成功');
        } elseif ($type == 1) {
            $order->expressname = $expressname;
            $order->expressno = $expressno;
            $order->save();
            $this->success('修改成功');
        } elseif ($order->orderstate == 4) {
            $this->error("请完成售后后再进行操作");
        }
        $this->error('没有权限操作');
    }

    //电子面单【单独】
    public function electronics()
    {
        $order_id = $this->request->param('order_id');
        $row = $this->model->field('o.id,oe.print_template')
            ->where('o.id', $order_id)
            ->alias('o')
            ->join('shop_order_electronics oe', 'oe.order_sn=o.order_sn and oe.status=0', 'LEFT')
            ->find();

        if ($row && !empty($row['print_template'])) {
            $this->success('获取成功', '', ['PrintTemplate' => $row->print_template]);
        }
        $res = [];
        $electronics_id = $this->request->param('electronics_id');
        try {
            $res = \addons\shop\library\KdApiExpOrder::create($order_id, $electronics_id);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if (!isset($res['Success']) || !$res['Success']) {
            $msg = isset($res['Reason']) ? $res['Reason'] : '请求失败';
            $this->error($msg);
        }
        //成功
        $this->success('开始打印', '', $res);
    }

    //批量打印
    public function prints()
    {
        $ids = $this->request->param('ids');
        if (empty($ids)) {
            $this->error('打印参数错误');
        }
        $order_ids = explode('_', $ids);
        if ($this->request->isPost()) {
            $electronics_id = $this->request->post('electronics_id');
            $param = [];
            //是否已获取
            $list = $this->model->field('o.id,oe.print_template')
                ->where('o.id', 'IN', $order_ids)
                ->alias('o')
                ->join('shop_order_electronics oe', 'oe.order_sn=o.order_sn and oe.status=0', 'LEFT')
                ->select();
            $has_ids = [];
            //获取过的
            if ($list) {
                foreach ($list as $item) {
                    if (!empty($item['print_template'])) {
                        $param[] = [
                            'PrintTemplate' => $item['print_template'],
                            'Success'       => true
                        ];
                        $has_ids[] = $item['id'];
                    }
                }
            }
            //剩余未获取的
            try {
                foreach (array_diff($order_ids, $has_ids) as $order_id) {
                    $res = \addons\shop\library\KdApiExpOrder::create($order_id, $electronics_id);
                    if ($res) {
                        $param[] = $res;
                    }
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功', '', $param);
        }
        $config = get_addon_config('shop');
        $this->assignconfig('shop', $config);
        $this->assignconfig('order_ids', $order_ids);
        $order = $this->model->with(['OrderGoods'])->where('id', 'IN', $order_ids)->select();
        $this->view->assign('order', $order);
        return $this->view->fetch();
    }

    //取消电子面单
    public function cancel_electronics()
    {
        $oe_id = $this->request->param('oe_id');
        $row = OrderElectronics::get($oe_id);
        if ($row['status'] == 1) {
            $this->error('电子面单已取消');
        }
        $res = \addons\shop\library\KdApiExpOrder::cancel($row);
        if (isset($res['Success']) && $res['Success']) {
            $row->status = 1;
            $row->save();
            $this->success('取消成功', '', $res);
        }
        $msg = isset($res['Reason']) ? $res['Reason'] : '取消失败';
        $this->error($msg);
    }

    //退款查询
    protected function refunded($order)
    {
        $config = \addons\epay\library\Service::getConfig($order['paytype']);
        $response = null;
        try {
            if ($order['paytype'] == 'wechat') {
                $response = \Yansongda\Pay\Pay::wechat($config)->find([
                    'type'         => in_array($order['method'], ['miniapp', 'app']) ? $order['method'] : '',
                    'out_trade_no' => $order['order_sn']
                ], 'refund');
            } elseif ($order['paytype'] == 'alipay') {
                $response = \Yansongda\Pay\Pay::alipay($config)->find([
                    'out_trade_no'   => $order['order_sn'],
                    'out_request_no' => $order['order_sn']
                ], 'refund');
            }
        } catch (\Exception $e) {
            $this->assign('refunded_info', '查询退款失败，' . $e->getMessage());
        }
        if ($order['paytype'] == 'wechat') {
            if ($response && $response['return_msg'] == 'OK') {
                $this->assign('refunded_info', '已成功退款：' . $response->refund_fee / 100 . '元。');
            }
        } elseif ($order['paytype'] == 'alipay') {
            if ($response && $response['msg'] == 'Success') {
                $this->assign('refunded_info', '已成功退款：' . $response->refund_amount . '元。');
            }
        } else {
            $this->assign('refunded_info', "未知支付类型");
        }
    }
}
